#include <QMenu>

#include "searchlineedit.h"
#include "searchpopup.h"

SearchLineEdit::SearchLineEdit(QWidget *parent) :
        Utils::FancyLineEdit(parent),
        m_popup(new SearchPopup(parent))
{
    setPlaceholderText(tr("Input to search"));
    setButtonPixmap(Left, QPixmap(":/core/images/magnifier.png"));
    setButtonVisible(Left, true);
    setButtonMenu(Left, createPrefixesMenu());

    m_popup->hide();
}

SearchLineEdit::~SearchLineEdit()
{
}

void SearchLineEdit::focusInEvent(QFocusEvent *e)
{
    Utils::FancyLineEdit::focusInEvent(e);

//    m_popup->move(mapToGlobal(QPoint(geometry().left(), geometry().bottom() + 3)));
//    m_popup->resize(width(), m_popup->sizeHint().height());
//    m_popup->show();
}

void SearchLineEdit::focusOutEvent(QFocusEvent *e)
{
    Utils::FancyLineEdit::focusOutEvent(e);

    if (!m_popup->hasFocus())
        m_popup->hide();
}

void SearchLineEdit::changePrefix()
{
    QString searchText = tr("<type here>");
    QAction * act = qobject_cast<QAction *>(sender());

    if (act) {
        QString filterStr = act->data().toString();
        QString currentText = text();

        if (!currentText.isEmpty()) {
            searchText = currentText;
            foreach (const QString &filterString, QStringList() << ":" << "?") {
                if (currentText.startsWith(filterString + QLatin1Char(' '))) {
                    searchText = currentText.mid(filterString.length()+1);
                    break;
                }
            }
        }
        setText(filterStr + QLatin1Char(' ') + searchText);
        setSelection(filterStr.length() + 1, searchText.length());
    }
}

QMenu * SearchLineEdit::createPrefixesMenu()
{
    QMenu * menu = new QMenu(this);
    QAction * a = 0;

    a = menu->addAction(tr("Local contacts"));
    a->setData(QString(":"));
    connect(a, SIGNAL(triggered()), this, SLOT(changePrefix()));
    menu->addSeparator();

    a = menu->addAction(tr("New Contact"));
    a->setData("?");
    connect(a, SIGNAL(triggered()), this, SLOT(changePrefix()));

    return menu;
}
